package project.pianpian.controller;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import project.pianpian.mapper.DemandMapper;
import project.pianpian.mapper.OrderMapper;
import project.pianpian.entity.Demand;
import project.pianpian.entity.Order;
import project.pianpian.utils.ReturnUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;

/**
 * Description:
 * Param:
 * return:
 * Author: HSY
 * Date:2022/12/26
 */
@RestController
@Slf4j
@RequestMapping("/main")
public class OrderAPI {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private DemandMapper demandMapper;

    @GetMapping("/orders/{id}")
    public JSONObject getOrderById(@PathVariable("id") int id)
    {
        Order order = orderMapper.getOrderById(id);
        JSONObject returnJSON = new JSONObject();
        returnJSON.put("order",order);
        return ReturnUtils.success(200,"获取订单成功",returnJSON);

    }

    @PostMapping("/orders")
    public JSONObject addOrder(@RequestParam int demandId, @RequestParam int contractor_id)
    {
        Demand demand = demandMapper.getDemandById(demandId);
        int employer_id = demand.getEmployer_id();
        int budget = demand.getBudget();
        String title = demand.getTitle();
        String describe = demand.getDescribe();
        int isFinish = 0;
        Date deadline = demand.getDeadline();
        Date time = new Date();
        Order order = new Order(employer_id,contractor_id,budget,title,describe,deadline,isFinish,time);

        int num=orderMapper.addOrder(order);
        if(num == 0)
            return ReturnUtils.fail(500,"接单失败");

        int flag = demandMapper.updateDemandStatus(demandId);
            if(flag==0){
                return ReturnUtils.success(200,"接单成功，但demand表修改失败");
            }
        return ReturnUtils.success(200,"接单成功");
    }

    @PutMapping("/orders/{id}")
    public JSONObject updateOrderStatus(@PathVariable("id") int id)
    {
        int num=orderMapper.updateOrderStatus(id);
        if(num == 0)
            return ReturnUtils.fail(500,"订单状态更新失败");

        return ReturnUtils.success(200,"订单状态更新成功");
    }


}
